const url = require('url');
const electron = require('electron')
const { dialog, remote } = require('electron');
const path = require('path');
const fs = require('fs');
const { ipcMain, BrowserWindow } = electron;
const watchApp = require('./exec');

function ProjectInit() {
	console.log("初始化监听项目")
	ipcMain.on('create-project', (event, data) => {
		console.log('【IPC】新建项目');
		dialog.showOpenDialog({
			title: '选择目录',
			defaultPath: '/Users/junyitan/Desktop/doctorwork/iPenguinDoctor_qa/dist/',
			buttonLabel: '确认选择',
			properties: ['openFile', 'openDirectory']
		}).then(({ filePaths }) => {
			console.log('%c 初始化目录', 'color: red', filePaths)
			const dir = filePaths[0]
			const filePath = path.resolve(dir, 'project.config.json')
			const content = fs.readFileSync(filePath, 'utf-8');
			const config = JSON.parse(content);
			if (config && config.appid) {
				console.log("文件读取成功")
				event.sender.send("create-finish", {
					success: true,
					data: {
						appid: config.appid,
						projectName: config.projectname,
						libVersion: config.libVersion,
						path: dir,
						cover: "https://pubimg.xingren.com/c1306c35-72b3-4515-87e2-c76f67e6034f.png",
					}
				})
				// TODO: 这里需要写文件

			} else {
				event.sender.send("create-finish", {
					success: false,
					data: "配置信息不正确"
				})
			}
		})
	});
	/**
	 * 导出代码
	 */
	ipcMain.on('export-code', (event, data) => {
		console.log('【IPC】导出代码');
		const { fileName, content } = data;
		dialog.showOpenDialog({
			title: "请选择您要保存的文件",
			defaultPath: '~/Downloads',
			buttonLabel: "导出",
			properties: ['openDirectory'],

		}).then(({ filePaths }) => {
			const dir = filePaths[0]
			if (dir) {
				fs.writeFileSync(`${dir}/${fileName}.test.js`, content)
				event.reply('export-code-success');
			}
		}).catch(err => {
			console.log(err)
		})

	});

}


function createWindow() {
	ipcMain.on('create-window', (event, data) => {
		let win = new BrowserWindow({
			width: 800,
			height: 600,
		})
		win.on('close', () => { win = null })
		win.loadURL('http://localhost:3000/#/gen')
	});
}

module.exports = function handleMessage(ipcMain) {
	ProjectInit();
	createWindow();
	watchApp(ipcMain);
}